package com.whfc.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Collection;
import java.util.regex.Pattern;

/**
 * @author xuguocheng
 * @desc
 * @date 2018-08-28
 */
public class CollectionElementPatternValidator implements ConstraintValidator<CollectionElementPattern, Collection<String>> {

    private Pattern pattern;

    @Override
    public void initialize(CollectionElementPattern constraintAnnotation) {
        String regex = constraintAnnotation.regexp();
        this.pattern = Pattern.compile(regex);
    }

    @Override
    public boolean isValid(Collection<String> collection, ConstraintValidatorContext context) {
        if (null != collection) {
            for (String value : collection) {
                if (!pattern.matcher(value).matches()) {
                    return false;
                }
            }
        }
        return true;
    }
}
